package com.glela.api.upload.qiniu.general;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import javax.imageio.stream.FileImageInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import com.glela.api.upload.util.UpLoadConfig;
import com.glela.common.util.DateUtil;
import com.glela.common.util.QrcodeUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

public class QiniuUtils {
	
	public static final Logger logger = LoggerFactory.getLogger(QiniuUtils.class);

	public static String  getToken(){
		Auth auth = Auth.create("A8JzrP6yp-DUa6WwLXanW-9Cj6bQvVvL_Rclyfl3","YXNw-ovb2WWWebXdi8609OLPFpS8SVPK7m8C93ea");
		return auth.uploadToken("xiaozhuangwang");
	}
	/**
	 * 删除qiniu服务器图片
	 * @param urlPath  图片路径
	 * @return
	 */
	public static boolean delete(String urlPath){
		
		Auth auth = Auth.create(UpLoadConfig.accessKey, UpLoadConfig.secretKey);
		 //实例化一个BucketManager对象
	    BucketManager bucketManager = new BucketManager(auth);
	    //要测试的空间和key，并且这个key在你空间中存在
	    try {   
		    bucketManager.delete(UpLoadConfig.bucket, urlPath);
		    return true;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("删除图片错误",e);
		}
		return false ;
	}
	
	/**
	 * 
	 * @Description: 上传图片
	 * @param  urlPath   要上传的图片路径  如 file/brand/
	 * @param  listfile  MultipartFile文件
	 * @param    
	 * @return String   "" 上传图片失败, 如果成功则显示上传路径   
	 * @throws
	 * @date 2015年9月11日
	 */
	public static String uploadByBytys64(String urlPath, byte[] b,String suffix) {
			try {
				UploadManager uploadManager = new UploadManager();
				String token = getToken();
				String realName = DateUtil.toString(new Date(),
						"yyyyMMddHHmmssSSS")+ "."+suffix;
				urlPath = urlPath+realName;
		        uploadManager.put(b, urlPath, token);
		    } catch (QiniuException e) {
		        Response r = e.response;
		        // 请求失败时简单状态信息
		        logger.error("气牛请求失败 " + r.toString());
		        try {
		            // 响应的文本信息
		        	logger.error(r.bodyString());
		        } catch (QiniuException e1) {
		            //ignore
		        }
		    } 
		return urlPath;
	}
	
	/**
	 * 校妆易宝二维码保存
	 * @param urlPath
	 * @param b
	 * @param suffix
	 * @param orderSn
	 * @return
	 */
	public static String uploadOrderQRCode(String urlPath, byte[] b,String suffix,String orderSn) {
		try {
			UploadManager uploadManager = new UploadManager();
			String token = getToken();
			String realName = orderSn + "."+suffix;
			urlPath = urlPath+realName;
			uploadManager.put(b, urlPath, token);
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时简单状态信息
			logger.error("气牛请求失败 " + r.toString());
			try {
				// 响应的文本信息
				logger.error(r.bodyString());
			} catch (QiniuException e1) {
				//ignore
			}
		} 
		return urlPath;
	}
	
	
	public static String uploadOrderQRCode(String urlPath, File f,String suffix,String orderSn) {
		try {
			UploadManager uploadManager = new UploadManager();
			String token = getToken();
			String realName = orderSn + "."+suffix;
			urlPath = urlPath+realName;
			uploadManager.put(f, urlPath, token);
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时简单状态信息
			logger.error("气牛请求失败 " + r.toString());
			try {
				// 响应的文本信息
				logger.error(r.bodyString());
			} catch (QiniuException e1) {
				//ignore
			}
		} 
		return urlPath;
	}
	
	
	/**
	 * 
	 * @Description: 上传图片
	 * @param  urlPath   要上传的图片路径  如 file/brand/
	 * @param  listfile  MultipartFile文件
	 * @param    
	 * @return String   "" 上传图片失败, 如果成功则显示上传路径   
	 * @throws
	 * @date 2015年9月11日
	 */
	public static String upload(String urlPath, MultipartFile listfile) {
			try {
				UploadManager uploadManager = new UploadManager();
				String token = getToken();
				String imgName =listfile.getOriginalFilename();
				String realName = DateUtil.toString(new Date(),
						"yyyyMMddHHmmssSSS")
						+ imgName.substring(imgName.lastIndexOf("."));
				urlPath = urlPath+realName;
		        uploadManager.put(listfile.getBytes(), urlPath, token);
//		        logger.info(res.toString());
//		        logger.info(res.bodyString());
//		        DefaultPutRet ret = res.jsonToObject(DefaultPutRet.class);
		    } catch (QiniuException e) {
		        Response r = e.response;
		        // 请求失败时简单状态信息
		        logger.error("气牛请求失败 " + r.toString());
		        try {
		            // 响应的文本信息
		        	logger.error(r.bodyString());
		        } catch (QiniuException e1) {
		            //ignore
		        }
		    } catch (IOException e) {
				logger.error(e.getMessage(),e);
				urlPath ="";
				//return getJsonResult(result, "操作成功", msg);
			}
		return urlPath;
	}
	
	/**
	 * 图片上传到七牛指定地点
	 * @param urlPath 保存地址 如：file/topserial/
	 * @param imgfile 图片文件
	 * @return  -1 请选择需要上传的图片 ；    -2 上传失败
	 */
	public static String upload(MultipartFile imgfile){
		String filepath = "" ;
		
		if (imgfile ==  null || imgfile.getSize() < 0){
			return  "-1" ;//请选择需要上传的图片
		}
		
		filepath = QiniuUtils.upload(UpLoadConfig.urlPath, imgfile);
		if ("".equals(filepath)) {
			return "-2";//上传失败
		}
		return filepath ;
	}
	
	/**
	 * 包含文件名了
	 * @date 2015年9月11日
	 */
	public static String uploadWithFileName(String urlPath, MultipartFile listfile) {
		try {
			UploadManager uploadManager = new UploadManager();
			String token = getToken();
			uploadManager.put(listfile.getBytes(), urlPath, token);
//			logger.info(res.toString());
//			logger.info(res.bodyString());
//		        DefaultPutRet ret = res.jsonToObject(DefaultPutRet.class);
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时简单状态信息
			logger.error(r.toString());
			try {
				// 响应的文本信息
				logger.error(r.bodyString());
			} catch (QiniuException e1) {
				//ignore
			}
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			urlPath ="";
			//return getJsonResult(result, "操作成功", msg);
		}
		return urlPath;
	}
	
	public static String getPayQrcode(String context,String order_sn)throws Exception {
		//String context = target_url+"?order_sn=" + order_sn;
		String path = "/temp/" + UUID.randomUUID().toString() + ".jpg";
		File f = new File(path);
		try {
			QrcodeUtils.gen(context, f.getAbsolutePath());
		}catch (Exception e) {
			logger.error("生成二维码出错,内容:{} , 错误原因: {}",context,e);
			throw new Exception("生成二维码出错");
		}
		String str =  null;
		try {
			str = QiniuUtils.uploadOrderQRCode("file/yeePay/", f, "jpg", UUID.randomUUID().toString()+ "_" +order_sn);
		}catch (Exception e) {
			logger.error("上传七牛错误 ,内容:{} , 错误原因: {}",context,e);
			throw new Exception("上传七牛错误");
		}finally {
			try {
				if(f.exists()) {
					f.delete();
				}
			}catch(Exception e) {
				logger.error("删除订单二维码临时文件异常, 订单号 : {}  , 异常详细信息 : {}",order_sn ,e);
			}
		}
		return str;
	}
	
	public static byte[] hex2byte(String s) {
		byte[] src = s.toLowerCase().getBytes();
		byte[] ret = new byte[src.length / 2];
		for (int i = 0; i < src.length; i += 2) {
			byte hi = src[i];
			byte low = src[i + 1];
			hi = (byte) ((hi >= 'a' && hi <= 'f') ? 0x0a + (hi - 'a') : hi - '0');
			low = (byte) ((low >= 'a' && low <= 'f') ? 0x0a + (low - 'a') : low - '0');
			ret[i / 2] = (byte) (hi << 4 | low);
		}
		return ret;
	}
	
	
	public static byte[] image2byte(File f) {
		byte[] data = null;
		FileImageInputStream input = null;
		try {
			input = new FileImageInputStream(f);
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int numBytesRead = 0;
			while ((numBytesRead = input.read(buf)) != -1) {
				output.write(buf, 0, numBytesRead);
			}
			data = output.toByteArray();
			output.close();
			input.close();
		} catch (FileNotFoundException ex1) {
			ex1.printStackTrace();
		} catch (IOException ex1) {
			ex1.printStackTrace();
		}
		return data;
	}
	 
}
